﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using kwzx.Data;
using System.Threading;
using kwzx.Common;
using System.IO;

namespace kwzx
{
    public partial class frmScmSyn : Form
    {
        public frmScmSyn()
        {
            InitializeComponent();
        }


        private void frmScmSyn_Load(object sender, EventArgs e)
        {
           // this.btnSynPerson.Enabled = false;
            this.rtFailInfo.Text = "如需同步部门，请点击完整同步按钮，如需同步流程中就餐人员,请先检查是否有人员可以同步 ";
            this.rtFailInfo.ForeColor = System.Drawing.Color.Red;

        }



        //同步人员
        private void btnSynPerson_Click(object sender, EventArgs e)
        {
            this.rtFailInfo.ForeColor = System.Drawing.Color.Black;
            this.dataGridView2.Visible = false;
            this.dataGridView1.Visible = true;
            rtFailInfo.Text = "";
            HXYKTEntities db = new HXYKTEntities();
            scm_mainEntities scm = new scm_mainEntities();
            CallProc call = new CallProc();
            new Thread(new ThreadStart(delegate
            {

                int count = user.Count();
                DBHelperEX dbHelper = new DBHelperEX();
                int id = 1;
                int failID = 0;
                foreach (var item in user)
                {
                    SetTextMessage(100 * id / count);
                    id++;
                    string sex = item.XB == null ? "男" : item.XB;
                    string photoPath = item.ZP == null ? "" : item.ZP;
                    if (photoPath == "" || !item.ZP.ToString().Contains("ftp"))
                    {
                        failID++;
                        rtFailInfo.Invoke(new Action(() =>
                        {
                            rtFailInfo.Text += "姓名" + item.ZSXM + "无相片路径不予同步" + Environment.NewLine;

                        }));
                        continue;

                    }
                    var userCount = user.Where(a => a.rybh == item.rybh).ToArray();
                    if (userCount.Length > 1)
                    {
                        failID++;
                        rtFailInfo.Invoke(new Action(() =>
                        {
                            rtFailInfo.Text += "姓名：" + item.ZSXM + "人员编号:" + item.rybh.ToString() + "重复个数" + userCount.Length + Environment.NewLine;

                        }));
                        continue;
                    }

                    //思路 在ftp文件夹下找到“姓名+身份证.jpg  然后下载该图片，如果该图片存在 一般都会存在
                    //判断是否有该人员的部门 如果没有 跳过，如果有 同步人员  同步结果 如果同步该人员有相片，
                    //则跳过 ，如果没有相片 因scm 照片下 先压缩，后裁剪，然后上传到指定的目录 上传方式为（ftp） 端口10086 
                    int supNum = photoPath.LastIndexOf("ftp") + 4;  //最后一个出现 在加上ftp/
                    photoPath = photoPath.Substring(supNum, photoPath.Length - supNum);
                    int userImginfo = photoPath.IndexOf("/") + 1;
                    string imgName = photoPath.Substring(userImginfo, photoPath.Length - userImginfo);
                    string kkzp = FileTran.DownloadFile(SPicUtils.path, imgName, photoPath);
                    string platName = SPicUtils.path + imgName;
                    string photoName = "";

                    if (File.Exists(platName))//
                    {
                        string deptID = item.DEPT_id.ToString();

                        dt_dep dep = scm.dt_dep.Where(a => a.dep_no_add == deptID).FirstOrDefault();
                        if (dep != null)
                        {

                            photoName = call.UserEx(item.rybh.ToString(), item.ZSXM.ToString(), 1, sex, item.sfzh.ToString(), 0, deptID);
                            if (!string.IsNullOrWhiteSpace(photoName))
                            {
                                //scm平台照片存放文件夹命名方式为人员序号除以1000
                                int folderName = int.Parse(photoName.Substring(0, photoName.Length - 4)) / 1000;
                                if (!Directory.Exists(SPicUtils.path + folderName))
                                {
                                    Directory.CreateDirectory(SPicUtils.path + folderName);
                                }
                                string scmphotoName = SPicUtils.path + folderName + "\\" + photoName;
                                string tmpImgPath = AppDomain.CurrentDomain.BaseDirectory + imgName;  //用于存放临时图片
                                //裁减图片原图片为平台原始图片,保存在scm平台根目录,因后面要压缩 故没有放在对应文件夹中
                                imgUtils.CutForCustom(SPicUtils.path + imgName, tmpImgPath, 140, 194, 0);
                                //压缩图片  原图片在scm平台图片根目录,压缩后图片在人员序号/1000的文件夹中，长,宽，质量
                                Common.CommonImg.CompressImage(tmpImgPath, scmphotoName, 194, 140, 60);
                                //imgUtils.GetReducedImage(exportPath + imgName, scmphotoName, 140, 194, 0);

                                //删除根目录图片
                                File.Delete(tmpImgPath);
                                FileInfo scmphoto = new FileInfo(scmphotoName);
                                FileTran.SaveFile(scmphoto, photoName, folderName.ToString() + "/", 10086);
                            }

                        }
                        else
                        {

                            this.Invoke((MethodInvoker)delegate
                      {
                          this.rtFailInfo.Text += item.ZSXM + "无部门名称" + Environment.NewLine; ;
                      });
                            continue;
                        }
                    }
                    else
                    {
                        failID++;
                        this.Invoke((MethodInvoker)delegate
                        {
                            if (item.rybh != null && item.sfzh != null)
                            {
                                //照片不存在进行同步
                                photoName = call.UserEx(item.rybh.ToString(), item.ZSXM.ToString(), 0, sex, item.sfzh.ToString(), 0, item.DEPT_id.ToString());


                                string log = string.Format("姓名:{0}身份证{1}无照片或者照片不匹配照片名:{2}" + Environment.NewLine, item.ZSXM, item.sfzh, imgName);
                                this.rtFailInfo.Text += log + Environment.NewLine; ;
                                Log.WriteInfo(log);

                            }
                            else
                            {

                                this.rtFailInfo.Text += item.ZSXM + "无人员编号" + Environment.NewLine; ;

                            }
                        });
                    }

                }
                rtFailInfo.Invoke(new Action(() =>
                {
                    rtFailInfo.Text += "同步人员信息成功" + Environment.NewLine;
                    rtFailInfo.Text += "共" + count + "条信息,其中同步成功" + (count - failID) + "条信息" + Environment.NewLine;
                }));
            }

             )).Start();
        }



        private void SetTextMessage(int ipos)
        {
            this.Invoke((MethodInvoker)delegate
            {
                this.labProgress.Text = ipos.ToString() + "/100";
                this.progressBar1.Value = Convert.ToInt32(ipos);
                if (ipos == 100)
                {
                    this.labProgress.Text = "导入完成";
                }
            });


        }


        //同步部门
        private void btnSynDept_Click(object sender, EventArgs e)
        {
            this.rtFailInfo.ForeColor = System.Drawing.Color.Black;
            this.dataGridView2.Visible = true;
            this.dataGridView1.Visible = false;
            this.rtFailInfo.Text = "";
            HXYKTEntities db = new HXYKTEntities();
            var bm = db.T_BM.ToList().OrderBy(a => a.SXH);
            int id = 1;
            this.dataGridView2.DataSource = bm;
            rtFailInfo.Text = "此次需要同步部门数据为" + bm.ToList().Count() + "条";
            new Thread(new ThreadStart(delegate
            {
                try
                {
                    foreach (var item in bm.ToList())
                    {
                        int ipos = 100 * id / bm.ToArray().Length;

                        SetTextMessage(ipos);
                        id++;
                        CallProc call = new CallProc();
                        if (item.GRPUP_ID != 83)
                        {
                            call.DeptEx(item.DEPT_id.ToString(), 1001, item.BMMC.ToString(), false);
                        }
                        else
                        {
                            if (item.SJBM == 0)
                            {
                                call.DeptEx(item.DEPT_id.ToString(), int.Parse(item.GRPUP_ID.ToString()), item.BMMC.ToString(), true);
                            }
                            else
                            {
                                call.DeptEx(item.DEPT_id.ToString(), int.Parse(item.SJBM.ToString()), item.BMMC.ToString(), true);
                            }

                        }
                    }
                }
                catch (Exception ex)
                {
                    string log = string.Format("同步部门失败,请联系软件维护人员");
                    this.rtFailInfo.Text += log + ex.ToString();
                    Log.WriteInfo(log);

                }

                rtFailInfo.Invoke(new Action(() =>
                {
                    rtFailInfo.Text += "同步部门信息成功";
                    Log.WriteInfo(rtFailInfo.Text);
                }));


            })).Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            frmScmDataSyns frm = new frmScmDataSyns();
            frm.ShowDialog();
        }


        private List<View_UserInfo> user;
        private void btnSyn_Click(object sender, EventArgs e)
        {
            this.rtFailInfo.ForeColor = System.Drawing.Color.Black;
            this.dataGridView2.Visible = false;
            this.dataGridView1.Visible = true;
            rtFailInfo.Text = "";
            HXYKTEntities db = new HXYKTEntities();
            scm_mainEntities scm = new scm_mainEntities();
            CallProc call = new CallProc();
            //一卡通 人员在scm 平台查找 如果有 说明是新增
            List<dt_user> listScmUser = scm.dt_user.ToList();
            List<View_UserInfo> viewuser = db.View_UserInfo.Where(a => a.ZP.Contains("ftp")).Where(a => a.DEPT_id != 304).ToList();
            foreach (var item in listScmUser)
            {
                var lackuser = viewuser.Where(a => a.rybh == item.user_no).FirstOrDefault();
                if (lackuser != null)
                {
                    viewuser.Remove(lackuser);
                }
            }


            this.rtFailInfo.Text = "此次可以同步的数据为" + viewuser.Count().ToString() + "条";

            this.dataGridView1.DataSource = viewuser;
            if (viewuser.Count > 0)
            {
              //  this.btnSynPerson.Enabled = true;
                user = viewuser;
            }

        }




        private List<jc_rw> jc_user;
        //就餐同步
        private void btnSys_Click(object sender, EventArgs e)
        {
            this.rtFailInfo.ForeColor = System.Drawing.Color.Black;
            this.dataGridView2.Visible = false;
            this.dataGridView1.Visible = true;
            rtFailInfo.Text = "";
            HXYKTEntities db = new HXYKTEntities();
            scm_mainEntities scm = new scm_mainEntities();
            CallProc call = new CallProc();
            //一卡通 人员在scm 平台查找 如果有 说明是新增
            List<dt_user> listScmUser = scm.dt_user.ToList();
            List<jc_rw> viewuser = db.jc_rw.Where(a => a.bname.Contains("S_jcsqb")).Where(a => a.zt == 0).ToList();
            foreach (var item in listScmUser)
            {
                var lackuser = viewuser.Where(a => a.rybh == item.user_no).FirstOrDefault();
                if (lackuser != null)
                {
                    viewuser.Remove(lackuser);
                }
            }


            this.rtFailInfo.Text = "此次可以同步的数据为" + viewuser.Count().ToString() + "条";

            this.dataGridView1.DataSource = viewuser;
            if (viewuser.Count > 0)
            {
              //  this.btnSynPerson.Enabled = true;
                jc_user = viewuser;
            }
        }


        //流程人员同步
        private void btnLiuSys_Click(object sender, EventArgs e)
        {
            this.rtFailInfo.ForeColor = System.Drawing.Color.Black;
            this.dataGridView2.Visible = false;
            this.dataGridView1.Visible = true;
            rtFailInfo.Text = "";
            HXYKTEntities db = new HXYKTEntities();
            scm_mainEntities scm = new scm_mainEntities();
            CallProc call = new CallProc();
            new Thread(new ThreadStart(delegate
            {

                int count = jc_user.Count();
                DBHelperEX dbHelper = new DBHelperEX();
                int id = 1;
                int failID = 0;
                foreach (var item in jc_user)
                {
                    SetTextMessage(100 * id / count);
                    id++;
                    string sex = item.XB == null ? "男" : item.XB;
                    string photoPath = item.ZP == null ? "" : item.ZP;
                    if (photoPath == "" || !item.ZP.ToString().Contains("ftp"))
                    {
                        failID++;
                        rtFailInfo.Invoke(new Action(() =>
                        {
                            rtFailInfo.Text += "姓名" + item.ZSXM + "无相片路径不予同步" + Environment.NewLine;

                        }));
                        continue;

                    }
                    var userCount = jc_user.Where(a => a.rybh == item.rybh).ToArray();
                    if (userCount.Length > 1)
                    {
                        failID++;
                        rtFailInfo.Invoke(new Action(() =>
                        {
                            rtFailInfo.Text += "姓名：" + item.ZSXM + "人员编号:" + item.rybh.ToString() + "重复个数" + userCount.Length + Environment.NewLine;

                        }));
                        continue;
                    }

                    //思路 在ftp文件夹下找到“姓名+身份证.jpg  然后下载该图片，如果该图片存在 一般都会存在
                    //判断是否有该人员的部门 如果没有 跳过，如果有 同步人员  同步结果 如果同步该人员有相片，
                    //则跳过 ，如果没有相片 因scm 照片下 先压缩，后裁剪，然后上传到指定的目录 上传方式为（ftp） 端口10086 
                    int supNum = photoPath.LastIndexOf("ftp") + 4;  //最后一个出现 在加上ftp/
                    photoPath = photoPath.Substring(supNum, photoPath.Length - supNum);
                    int userImginfo = photoPath.IndexOf("/") + 1;
                    string imgName = photoPath.Substring(userImginfo, photoPath.Length - userImginfo);
                    string kkzp = FileTran.DownloadFile(SPicUtils.path, imgName, photoPath);
                    string platName = SPicUtils.path + imgName;
                    string photoName = "";

                    if (File.Exists(platName))//
                    {
                        string deptID = item.DEPT_id.ToString();

                        dt_dep dep = scm.dt_dep.Where(a => a.dep_no_add == deptID).FirstOrDefault();
                        if (dep != null)
                        {

                            photoName = call.UserEx(item.rybh.ToString(), item.ZSXM.ToString(), 1, sex, item.sfzh.ToString(), 0, deptID);
                            ResultSys(item.kwzxrwid);
                            if (!string.IsNullOrWhiteSpace(photoName))
                            {
                                //scm平台照片存放文件夹命名方式为人员序号除以1000
                                int folderName = int.Parse(photoName.Substring(0, photoName.Length - 4)) / 1000;
                                if (!Directory.Exists(SPicUtils.path + folderName))
                                {
                                    Directory.CreateDirectory(SPicUtils.path + folderName);
                                }
                                string scmphotoName = SPicUtils.path + folderName + "\\" + photoName;
                                string tmpImgPath = AppDomain.CurrentDomain.BaseDirectory + imgName;  //用于存放临时图片
                                //裁减图片原图片为平台原始图片,保存在scm平台根目录,因后面要压缩 故没有放在对应文件夹中
                                imgUtils.CutForCustom(SPicUtils.path + imgName, tmpImgPath, 140, 194, 0);
                                //压缩图片  原图片在scm平台图片根目录,压缩后图片在人员序号/1000的文件夹中，长,宽，质量
                                Common.CommonImg.CompressImage(tmpImgPath, scmphotoName, 194, 140, 60);
                                //imgUtils.GetReducedImage(exportPath + imgName, scmphotoName, 140, 194, 0);

                                //删除根目录图片
                                File.Delete(tmpImgPath);
                                FileInfo scmphoto = new FileInfo(scmphotoName);
                                FileTran.SaveFile(scmphoto, photoName, folderName.ToString() + "/", 10086);
                            }

                        }
                        else
                        {

                            this.Invoke((MethodInvoker)delegate
                            {
                                this.rtFailInfo.Text += item.ZSXM + "无部门名称" + Environment.NewLine; ;
                            });
                            continue;
                        }
                    }
                    else
                    {
                        failID++;
                        this.Invoke((MethodInvoker)delegate
                        {
                            if (item.rybh != null && item.sfzh != null)
                            {
                                //照片不存在进行同步
                                photoName = call.UserEx(item.rybh.ToString(), item.ZSXM.ToString(), 0, sex, item.sfzh.ToString(), 0, item.DEPT_id.ToString());

                                ResultSys(item.kwzxrwid);
                                string log = string.Format("姓名:{0}身份证{1}无照片或者照片不匹配照片名:{2}" + Environment.NewLine, item.ZSXM, item.sfzh, imgName);
                                this.rtFailInfo.Text += log + Environment.NewLine; ;
                                Log.WriteInfo(log);

                            }
                            else
                            {

                                this.rtFailInfo.Text += item.ZSXM + "无人员编号" + Environment.NewLine; ;

                            }
                        });
                    }

                }
                rtFailInfo.Invoke(new Action(() =>
                {
                    rtFailInfo.Text += "同步人员信息成功" + Environment.NewLine;
                    rtFailInfo.Text += "共" + count + "条信息,其中同步成功" + (count - failID) + "条信息" + Environment.NewLine;
                }));
            }

             )).Start();
        }


        /// <summary>
        /// 如果同步成功 卡务中心任务表状态值为1
        /// </summary>
        /// <param name="rwid"></param>
        /// <returns></returns>
        private bool ResultSys(int rwid)
        {
            HXYKTEntities db = new HXYKTEntities();
            var K_kwzxrw = db.K_kwzxrw.Where(a => a.kwzxrwid == rwid).FirstOrDefault();
            if (K_kwzxrw != null)
            {
                K_kwzxrw.zt = 1;
            }

            //添加到一卡通平台白名单
            scm_mainEntities scm = new scm_mainEntities();
            var yktUser = db.Kcard_UserBM.Where(a => a.user_id == K_kwzxrw.userid).FirstOrDefault();
            Scm_bmd bmd = db.Scm_bmd.Where(a => a.user_RYBH == yktUser.rybh).FirstOrDefault();
            if (bmd == null && yktUser != null)
            {
                bmd.Dept_ID = yktUser.DEPT_id;
                bmd.Dept_Name = yktUser.BMMC;
                bmd.Group_ID = yktUser.GRPUP_ID;
                bmd.userID = yktUser.user_id;
                bmd.user_RYBH = yktUser.rybh;
                bmd.XM = yktUser.XM;
                bmd.XB = yktUser.XB;
                bmd.IDCard = yktUser.sfzh;
                bmd.UBY = int.Parse(yktUser.UBY);
                bmd.ZP = yktUser.ZP;
                var jcModle = db.S_jcsqb.Where(a => a.ryjcfid == K_kwzxrw.bid).FirstOrDefault();
                if (jcModle != null)
                {
                    bmd.PayType = jcModle.sfbz == "按正常收费" ? 1 : 2;
                }

                bmd.Operatime = DateTime.Now;
                bmd.remark1 = "0";  // 0表示为先scm平台插入
                //bmd.scm_userseriral = Convert.ToInt32(scmuser.user_serial);
                //bmd.scm_userkh = scmuser.user_card;
                db.AddToScm_bmd(bmd);
                db.SaveChanges();
            }
            return true;
        }

    }
}
